package com.aj.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.widget.ListView;

import com.aj.activity.adapter.DirExplorerAdapter;
import com.aj.utils.Contants;
import com.aj.utils.MobileUtil;

/**
 * The Class FileExplorerActivity.
 */
public class DirExplorerActivity extends BaseActivity {

	/** The Constant TAG. */
	public static final String TAG = DirExplorerActivity.class.getName();

	/** The instance. */
	public static DirExplorerActivity instance;

	/** The m list view. */
	private ListView mListView = null;

	/** The adapter. */
	private DirExplorerAdapter adapter = null;

	/** The filter. */
	private String filter = "";

	/** The file map. */
	private LinkedHashMap<String, List<File>> fileMap = new LinkedHashMap<String, List<File>>();

	/** The search thread. */
	private Thread searchThread = null;

	/** The Constant MSG_INIT_LIST. */
	public static final int MSG_INIT_LIST = 0;

	/**
	 * On create.
	 * 
	 * @param savedInstanceState
	 *            the saved instance state
	 * @version
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_dir_explorer);
		instance = this;
		initViews();
		showProgressDialog();
		searchThread = new Thread(searchRunnable);
		searchThread.start();
	}

	/**
	 * Inits the views.
	 * 
	 * @version
	 */
	private void initViews() {
		mListView = (ListView) findViewById(R.id.lvShow);
		String fileType = instance.getIntent().getStringExtra(
				Contants.FILY_TYPE_PARAMS);
		if (fileType != null && fileType.equals(Contants.TYPE_IMAGE)) {
			setActionBarTitle(R.string.dir_photo_file_title_text);
		} else if (fileType != null && fileType.equals(Contants.TYPE_VEDIO)) {
			setActionBarTitle(R.string.dir_photo_video_title_text);
		}
	}

	/** The handler. */
	Handler handler = new Handler(new Handler.Callback() {

		@Override
		public boolean handleMessage(Message msg) {
			if (msg.what == MSG_INIT_LIST) {
				adapter = new DirExplorerAdapter(instance, fileMap, getIntent()
						.getStringExtra(Contants.ZONE_ID_PARAMS), getIntent()
						.getStringExtra(Contants.USER_ID_PARAMS));
				mListView.setAdapter(adapter);
				dimissProgressDialog();
			}
			return true;
		}
	});
	/** The search runnable. */
	Runnable searchRunnable = new Runnable() {

		@Override
		public void run() {
			filter = instance.getIntent().getStringExtra(
					Contants.FILY_TYPE_PARAMS);
			if (filter == null) {
				// filter = ".*\\.(jpg|jpeg|bmp|gif|png|3gp)$";
				filter = "image/jpeg,image/png,image/x-ms-bmp,image/jpg,image/gif,video/3gpp";
				findFileBySys(fileMap, MobileUtil.getFilePath(), filter);
			} else if (filter.equals(Contants.TYPE_IMAGE)) {
				// filter = ".*\\.(jpg|jpeg|bmp|gif|png)$";
				filter = "image/jpeg,image/png,image/x-ms-bmp,image/jpg,image/gif";
				findFileBySys(fileMap, MobileUtil.getFilePath(), filter);
			} else if (filter.equals(Contants.TYPE_VEDIO)) {
				// filter = ".*\\.(3gp)$";
				filter = "video/3gpp";
				findFileBySys(fileMap, MobileUtil.getFilePath(), filter);
			}
			handler.sendEmptyMessage(MSG_INIT_LIST);

		}
	};

	/**
	 * Find file.根据过滤条件生成文件过滤结果集（递归方法）
	 * 
	 * @param fileMap
	 *            the file map
	 * @param filePath
	 *            the file path
	 * @param filter
	 *            the filter
	 * @version
	 */
	private void findFile(LinkedHashMap<String, List<File>> fileMap,
			String filePath, String filter) {

		if (filePath == null) {
			filePath = MobileUtil.getFilePath();
		}

		File files = new File(filePath);
		if ((!files.canRead() || files.isHidden())) {
			return;
		}
		List<File> list = new ArrayList<File>();

		for (File file : files.listFiles()) {
			if (file.isDirectory()) {
				findFile(fileMap, file.getPath(), filter);
			} else {
				if (file.getName().toLowerCase().matches(filter)
						&& file.length() <= 5 * 1024 * 1024
						&& file.length() > 0) {
					list.add(file);
				} else {
					continue;
				}
			}
		}
		if (list.size() > 0) {
			fileMap.put(files.getAbsolutePath(), list);
		}
	}

	/**
	 * 根据过滤条件生成文件过滤结果集（使用系统图库）
	 * 
	 * @param fileMap
	 *            the file map
	 * @param filePath
	 *            the file path
	 * @param filter
	 *            the filter
	 * @version
	 */
	private void findFileBySys(LinkedHashMap<String, List<File>> fileMap,
			String filePath, String filter) {
		Uri mImgUri;
		if (filter.indexOf("image") != -1 && filter.indexOf("video") == -1) {
			mImgUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
		} else if (filter.indexOf("image") == -1
				&& filter.indexOf("video") != -1) {
			mImgUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
		} else {
			mImgUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
		}

		ContentResolver mContentResolver = instance.getContentResolver();
		String[] selectionArgs = filter.split(",");

		String selection = "";

		for (int i = 0; i < selectionArgs.length; i++) {
			selection += MediaStore.Images.Media.MIME_TYPE + "=? or ";
		}
		selection = selection.substring(0, selection.lastIndexOf(" or"));

		// new String[] {"image/jpeg", "image/png"}
		Cursor mCursor = mContentResolver.query(mImgUri, null, selection,
				selectionArgs, MediaStore.Images.Media.DATE_MODIFIED);

		if (mCursor == null) {
			return;
		}

		while (mCursor.moveToNext()) {
			String path = mCursor.getString(mCursor
					.getColumnIndex(MediaStore.Images.Media.DATA));
			File file = new File(path);
			String parentPath = file.getParentFile().getAbsolutePath();

			if (file.length() <= 5 * 1024 * 1024 && file.length() > 0) {
				if (!fileMap.containsKey(parentPath)) {
					List<File> list = new ArrayList<File>();
					list.add(file);
					fileMap.put(parentPath, list);
				} else {
					fileMap.get(parentPath).add(file);
				}
			}
		}

	}

	@Override
	protected void onResume() {
		super.onResume();
	}
}
